
class QCmdQueue:
    def __init__(self, SyncMode=True):
        self.SyncMode = SyncMode
        self.InputCmdQueue = CmdQueueInit()    # user input command
        self.SendOutCmdBuffer = CmdQueueInit() # cmdQueue buffer for sync
        self.ExeCmdQueue = CmdQueueInit()      # execution command

    def Clear(self):
        if self.SyncMode:
            inputCmdQueue = self.SendOutCmdBuffer
        else:
            inputCmdQueue = self.InputCmdQueue
        inputCmdQueue.clear()
        self.ExeCmdQueue.clear()

    # push input command into InputCmdQueue
    def InputCmdQueuePush(self, memberID, cmdID, param):
        CmdQueuePush(self.InputCmdQueue, memberID, cmdID, param)

    # push execution command into ExeCmdQueue
    def ExeCmdQueuePush(self, memberID, cmdID, param):
        CmdQueuePush(self.ExeCmdQueue, memberID, cmdID, param)

    # load SendOutCmdBuffer from InputCmdQueue
    def SendOutCmdBufferLoad(self):
        self.SendOutCmdBuffer = self.InputCmdQueue
        self.InputCmdQueue = {}

    def SendOutCmdBufferGet(self):
        return self.SendOutCmdBuffer

    # for sync mode:server only
    def SendOutCmdBufferMerge(self, cmdQueue):
        CmdQueueMerge(self.SendOutCmdBuffer, cmdQueue)

    def ExeCmdQueueMerge(self, SendOutCmdBuffer=None):
        if self.SyncMode:
            if SendOutCmdBuffer is None:
                inputCmdQueue = self.SendOutCmdBuffer
            else:
                inputCmdQueue = SendOutCmdBuffer
        else:
            inputCmdQueue = self.InputCmdQueue
        CmdQueueMerge(self.ExeCmdQueue, inputCmdQueue)

    # get CmdList from ExeCmdQueue [CmdParser]
    def ExeCmdListExtract(self):
        cmdList = CmdListExtract(self.ExeCmdQueue)
        return cmdList

# internal function
def CmdQueueInit():
    return {}

def CmdQueuePush(cmdQueue, memberID, cmdID, param):
    if cmdQueue.has_key(memberID): # add item
        cmdQueue[memberID].append([cmdID,param])
    else: # create entry and add item
        cmdQueue[memberID] = [ [cmdID,param] ]

def CmdQueueMerge(tragerCmdQueue, fromCmdQueue):
    for (memberID,cmdItem) in fromCmdQueue.items():
        if tragerCmdQueue.has_key(memberID):
            tragerCmdQueue[memberID].extend(cmdItem)
        else:
            tragerCmdQueue[memberID] = cmdItem

def CmdListExtract(cmdQueue):
    cmdList = []
    for (key, item) in cmdQueue.items():
        for cmdInfo in item:
            cmdItme = {"memberID":key, "cmdID":cmdInfo[0], "param":cmdInfo[1] }
            cmdList.append(cmdItme)
    return cmdList
